using System.Collections.Generic;
using System.Linq;
using Webbness.Mvc.Models;

namespace Webbness.Mvc.SubSonic
{
    public class UserRepository<TUser, TJoin, TRole> : SimpleTypedRepository<TUser>
        where TRole : SecurityRole<TRole, TJoin, TUser>, new()
        where TUser : SecurityUser<TUser, TJoin, TRole>, new()
        where TJoin : SecurityUserInRole<TRole, TJoin, TUser>, new()
    {
        public TUser GetUserByUserName(string username)
        {
            return Repository.Repo.Single<TUser>(u => u.UserName == username);
        }

        public TUser GetNew()
        {
            return new TUser();
        }

        public TUser GetUserByUserID(int userid)
        {
            return Single(userid);
        }

        public TUser GetUserByEmail(string email)
        {
            return Single(u => u.Email == email);
        }

        public int Delete(TUser user)
        {
            return Delete(user.Id);
        }

        public List<TUser> FindAllUsers()
        {
            return All().ToList();
        }

        public int GetNumberOfUsersOnline()
        {
            return All().Count(u => u.IsOnLine);
        }

        public List<TUser> FindMatchingUsers(string usernameToMatch)
        {
            IQueryable<TUser> query = from users in Repository.Repo.All<TUser>() where users.UserName.Contains(usernameToMatch) select users;
            return query.ToList();
        }

        public List<TUser> FindMatchingEmails(string emailToMatch)
        {
            IQueryable<TUser> query = from users in Repository.Repo.All<TUser>() where users.Email.Contains(emailToMatch) select users;
            return query.ToList();
        }
    }
}